# encoding: utf-8
# @author: wangxin
# @software: garner
# @file: registerViews.py
# @time: 2025/2/17 19:26
import re
import time

from http.client import responses


import pymysql
from django.contrib.auth import login

from django.http import HttpResponse, JsonResponse, HttpResponseBadRequest
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
#使用pandas处理数据


# 导入StreamingHttpResponse类，用于处理需要流式响应的HTTP请求
from django.http import  StreamingHttpResponse
from django_redis import get_redis_connection

from libs.captcha.captcha import captcha
from user import models


class registerView(View):
    def get(self, request):
        #返回渲染界面
        return render(request, 'register.html')
    def post(self,request):

        mobile = request.POST.get('mobile')
        password=request.POST.get('password')
        password2=request.POST.get('password2')
        sms_code=request.POST.get('sms_code')
        if not all([mobile,password,password2,sms_code]):
            return HttpResponseBadRequest('请输入完整的注册信息')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseBadRequest('请输入正确的手机号码')
        if not re.match(r'^[0-9A-Za-z]{6,20}$', password):
            return HttpResponseBadRequest('请输入6-20位的密码')
        if password != password2:
            return HttpResponseBadRequest('两次密码不一致')
        redis_conn = get_redis_connection('default')
        sms_code_redis = redis_conn.get('sms_code:%s' % mobile)
        if sms_code_redis is None:
            return HttpResponseBadRequest('短信验过期')
        if sms_code != sms_code_redis.decode():
            return HttpResponseBadRequest('短信验证码错误')
        #保存注册数据

        try:
            user = models.User.objects.create_user(username=mobile,mobile=mobile, password=password)  # 初始时不设置密码
            #user.set_password(password)  # 使用 Django 的 set_password 方法来安全设置密码

            # 此函数的主要作用是将用户对象与请求关联起来，并在会话中记录用户状态，以便后续的请求可以识别用户
            login(request, user)

        except Exception as e:
            print(e)
            return HttpResponseBadRequest('手机号码重复')
        responses = redirect(reverse('index'))
        # 设置响应中的Cookie，用于持久化用户身份
        responses.set_cookie('username', user.username, max_age=3600 * 24 * 7)

        #注册成功，重定向到首页
        return  responses





class imageCodeView(View):
    def get(self, request):
        uuid = request.GET.get('uuid')
        if uuid is None:
            return HttpResponseBadRequest('请求参数错误')
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection('default')
        redis_conn.setex("image_code:%s" % uuid, 300, text)
        # 返回响应，将生成的图片以content_type为image/jpeg的形式返回给请求
        return HttpResponse(image, content_type='image/jpeg')



